<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>编辑关键词自动回复</title>
    <link rel="stylesheet" href="../assets/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../assets/style/admin.css">
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <script src="../assets/layui/layui.js"></script>
    <script src="../assets/js/common.js"></script>
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script src="../common/header.js"></script>
    <!-- 内容主体区域 -->
    <div id="LAY_app_body">
        <div class="layui-fluid">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
                    <div class="layui-card">
                        <div class="layui-card-header">编辑关键词自动回复</div>
                        <div class="layui-card-body">
                            <form class="layui-form" action="">
                                <input type="hidden" name="id" value="0">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">状态</label>
                                    <div class="layui-input-block">
                                        <input type="radio" name="status" value="0" title="禁用" lay-filter="status">
                                        <input type="radio" name="status" value="1" title="启用" checked
                                               lay-filter="status">
                                    </div>
                                </div>
                                <div class="layui-form-item" hidden>
                                    <label class="layui-form-label">类型</label>
                                    <div class="layui-input-block">
                                        <input type="radio" name="content_type" value="1" title="文字"
                                               lay-filter="content_type">
                                        <input type="radio" name="content_type" value="3" title="图片"
                                               lay-filter="content_type">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">回复间隔</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="interval_minute" lay-verify="interval_minute"
                                               autocomplete="off" placeholder="相同关键词触发回复的间隔时间" class="layui-input"
                                               value="60">
                                    </div>
                                    <label class="layui-form-mid layui-word-aux">单位：分钟，相同关键词触发回复的间隔时间，不能低于10分钟</label>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">回复执行</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="delay_minute" lay-verify="delay_minute"
                                               autocomplete="off" placeholder="多少分钟后执行回复" class="layui-input" value="0">
                                    </div>
                                    <label class="layui-form-mid layui-word-aux">单位：分钟，几分钟后执行回复，0表示立即回复</label>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">关键词</label>
                                    <div class="layui-input-inline" style="width: 500px;">
                                        <input type="text" name="name" lay-verify="name" autocomplete="off"
                                               placeholder="请输入关键词，多个关键词用英文逗号分隔" value="" class="layui-input">
                                       </div>
                                    <label class="layui-form-mid layui-word-aux">多个关键词用英文逗号分隔</label>
                                </div>
                                <div id="messageBlock"></div>
                                <div class="layui-form-item"><label class="layui-form-label"></label>
                                    <button type="button" class="layui-btn layui-btn-normal layui-btn-sm"
                                            onclick="addContent();">新增文字
                                    </button>
                                    <button type="button" class="layui-btn layui-btn-normal layui-btn-sm"
                                            onclick="addImage();">新增图片
                                    </button>
                                    <button type="button" class="layui-btn layui-btn-normal layui-btn-sm"
                                            onclick="addAudio();">新增语音
                                    </button>
                                </div>
                                <div class="layui-form-item">
                                    <hr class="layui-bg-gray">
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-input-block">
                                        <a class="layui-btn" lay-submit lay-filter="formSubmit">提交</a>
                                        <a class="layui-btn layui-btn-primary" href="index.html">取消</a>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        var displayMessage;
        var getMessageHtml;
        var removeMessageBtn;
        var addContent;
        var displayContent;
        var messageCount = 0;
        var segmentCount = 0;
        var messageLimit = 20;
        var messageNum = 0;
        var displayImage;
        var addImage;
        var getMessages;
        var addAudio;
        layui.use(['form', 'upload'], function () {
            var $ = layui.$
                , form = layui.form
                , upload = layui.upload;

            form.verify({
                status: function (value) {
                    var status = $("input[ name='status' ]:checked ").val();
                    if (status == undefined) {
                        return '请选择状态';
                    }
                },
                name: function (value) {
                    var name = $("input[ name='name' ]").val();
                    if (name == '') {
                        return '请输入文字';
                    }
                },
                interval_minute: function (value) {
                    var interval_minute = $("input[ name='interval_minute' ]").val();
                    if (interval_minute < 10) {
                        return '间隔时间不能小于10分钟';
                    }
                },
                delay_minute: function (value) {
                    var delay_minute = $("input[ name='delay_minute' ]").val();
                    if (delay_minute < 0) {
                        return '延时回复时间不能小于0分钟';
                    } else if (delay_minute > 60) {
                        return '延时回复时间不能大于60分钟';
                    }
                },
                content: function (value) {
                    if (value.length < 2) {
                        return '自动回复内容不能少于2个字符';
                    } else if (value.length > 2000) {
                        return '自动回复内容不能超过2000个字符';
                    }
                }
            });

            //监听提交
            form.on('submit(formSubmit)', function (data) {
                var content = buildMessageJson();
                layer.msg('提交中', {
                    shadeClose: false
                    , icon: 16
                    , shade: 0.01
                });
                var post = {
                    id: data.field.id,
                    name: data.field.name,
                    status: data.field.status,
                    content: content,
                    sort: data.field.sort,
                    interval_minute: data.field.interval_minute,
                    delay_minute: data.field.delay_minute
                };
                // console.log(post);
                $.ajax({
                    type: "POST",
                    url: "/auto_reply/save4/?type=3",
                    data: post,
                    success: function (response) {
                        var dataObj = $.parseJSON(response);
                        if (dataObj.code === 0) {
                            layer.msg('数据提交成功', {icon: 6});
                            setTimeout(function () {
                                location.href = '/auto_reply/index';
                            }, 1000);
                        } else {
                            layer.msg(dataObj.msg, {icon: 5});
                        }
                    },
                    error: function (request, status, error) {
                        layer.msg('哦噢，网络开小差了', {icon: 5});
                    }
                });
                return false;
            });

            //普通图片上传
            var uploadInst = function (thisMessageCount) {
                upload.render({
                    elem: '#test' + thisMessageCount + ''
                    , url: '/auto_reply/upload'
                    , field: 'image'
                    , accept: 'file' //普通文件
                    , exts: 'jpg|jpeg|png' //只允许上传图片
                    , size: 1024 * 4 //限制文件大小，单位 KB
                    , before: function (obj) {
                        //预读本地文件示例，不支持ie8
                        obj.preview(function (index, file, result) {
                            $('#demo' + thisMessageCount + '').attr('src', result); //图片链接（base64）
                            // $('#image_list').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img" style="width: 100px;">');
                        });
                    }
                    , done: function (res) {
                        //如果上传失败
                        if (res.code == 0) {
                            addImageHiddenField(res.value, thisMessageCount);
                            $('#demoText' + thisMessageCount + '').append('<labe>' + res.msg + '</labe>');
                            //$('#image_list').append('<img id="imagePreview'+imageNum+'" num="'+imageNum+'" src="//'+ res.value +'" alt="'+ res.origin +'" class="layui-upload-img" style="width: 100px;">');
                            // $('#image_list').append('<labe>'+res.msg+'</labe>');
                        }

                        if (res.code > 0) {
                            return layer.msg('上传失败');
                        }
                        //上传成功
                    }
                    , error: function () {
                        //演示失败状态，并实现重传
                        var demoText = $('#demoText');
                        demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                        demoText.find('.demo-reload').on('click', function () {
                            uploadInst.upload();
                        });
                    }
                });
            };

            //语音上传
            var uploadAudio = function (thisMessageCount) {
                upload.render({
                    elem: '#test' + thisMessageCount + ''
                    , url: '/auto_reply/uploadAudio'
                    , field: 'audio'
                    , acceptMime: 'mp3'
                    , accept: 'audio' //普通文件
                    , exts: 'mp3' //只允许上传
                    , size: 1024 * 5 //限制文件大小，单位 KB
                    , before: function (obj) {
                        //预读本地文件示例，不支持ie8
                        obj.preview(function (index, file, result) {
                            $('#demo' + thisMessageCount + '').attr('src', result); //图片链接（base64）
                            // $('#image_list').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img" style="width: 100px;">');
                        });
                    }
                    , done: function (res) {
                        //如果上传失败
                        if (res.code == 0) {
                            addAudioHiddenField(res.value, thisMessageCount);
                            $('#demoText' + thisMessageCount + '').append('<labe>' + res.msg + '</labe>');
                            //$('#image_list').append('<img id="imagePreview'+imageNum+'" num="'+imageNum+'" src="//'+ res.value +'" alt="'+ res.origin +'" class="layui-upload-img" style="width: 100px;">');
                            // $('#image_list').append('<labe>'+res.msg+'</labe>');
                        }

                        if (res.code > 0) {
                            return layer.msg('上传失败');
                        }
                        //上传成功
                    }
                    , error: function () {
                        //演示失败状态，并实现重传
                        var demoText = $('#demoText3');
                        demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                        demoText.find('.demo-reload').on('click', function () {
                            uploadAudio(thisMessageCount);
                        });
                    }
                });
            };

            var addImageHiddenField = function (value, thisSegmentCount) {
                // var html = '<input type="hidden" class="file_name" name="file_name" value="'+value+'">';
                // $('#imageHiddenBlock'+thisSegmentCount+'').append(html);
                $('#file_name' + thisSegmentCount + '').val(value);

            };

            var addAudioHiddenField = function (value, thisSegmentCount) {
                $('#file_name' + thisSegmentCount + '').val(value);
            };

            form.on('radio(content_type)', function (data) {
                // console.log(data.elem); //得到radio原始DOM对象
                // console.log(data.value); //被点击的radio的value值
                var type = data.value;
                if (type == 1) {
                    $('#content_block').show();
                } else {
                    $('#content_block').hide();
                    // $('#image_block').show();
                }

                if (type == 2) {
                    $('#audio_block').show();
                } else {
                    $('#audio_block').hide();
                }

                if (type == 3) {
                    $('#image_block').show();
                } else {
                    $('#image_block').hide();
                }
            });


            displayContent = function (auto_replyId, name, content, type, auto_reply_item_id, item_sort) {
                content = decodeURI(content);
                if (messageNum >= messageLimit) {
                    layer.alert('当前组最多只能添加' + messageLimit + '条验证消息');
                    return false;
                }
                // manageMessageNum('add');
                messageCount++;
                var thisMessageCount = messageCount;
                var messageHtml = '<div id="message' + thisMessageCount + '" class="layui-form-item message-line">';
                // messageHtml += '<input type="hidden" name="auto_replyId" value="' + auto_replyId + '">';
                // messageHtml += '<div class="layui-inline"><label class="layui-form-label">自动回复' + thisMessageCount + ':</label></div>';
                messageHtml += '<div class="layui-inline">';

                if (content) {
                    messageHtml += getMessageHtml(name, content, auto_replyId, type, auto_reply_item_id, item_sort);
                } else {
                    messageHtml += addSegmentBtn(thisMessageCount, type, 0);
                }
                messageHtml += removeMessageBtn(thisMessageCount);
                messageHtml += '</div>';
                messageHtml += '</div>';
                // messageHtml += '<div class="layui-form-item"><hr class="layui-bg-gray"></div>';
                messageHtml += '</div>';
                $('#messageBlock').append(messageHtml);
                if (type == 'image') {
                    uploadInst(thisMessageCount);
                } else if (type == 'audio') {
                    uploadAudio(thisMessageCount);

                }
                form.render();
                if (content) {
                    addImageHiddenField(content, thisMessageCount);
                }
            };

            getMessageHtml = function (name, content, auto_replyId, type, auto_reply_item_id, item_sort) {
                segmentCount++;
                var thisSegmentCount = segmentCount;
                var html = '';
                // var width = 350;

                html += '<div class="layui-input-inline segment-item" style="width: 850px;" id="segment' + thisSegmentCount + '">';
                if (type == 'image') {
                    if (content != '') {
                        html += inputImageSegment(thisSegmentCount, content, auto_replyId, auto_reply_item_id, item_sort);
                    } else {
                        html += inputImageSegment(thisSegmentCount, '', '', 0);
                    }
                } else if (type == 'audio') {
                    if (content != '') {
                        html += inputAudioSegment(thisSegmentCount, content, auto_replyId, auto_reply_item_id, item_sort);
                    } else {
                        html += inputAudioSegment(thisSegmentCount, '', '', 0);
                    }
                } else {
                    if (content != '') {
                        html += inputContentSegment(thisSegmentCount, content, auto_reply_item_id, item_sort);
                    } else {
                        html += inputContentSegment(thisSegmentCount, '', 0);
                    }
                }
                // if (content != '') {
                //     html += delAutoReplyBtn(auto_replyId);
                // }
                html += '</div>';
                return html;
            };

            // var inputNameSegment = function (thisSegmentCount, name) {
            //     return '<label class="layui-form-label">状态名</label><div class="layui-input-inline" style="width: 100px;"><input type="text" id="segmentPost' + thisSegmentCount + '" name="name" placeholder="请输入文字" required lay-verify="required" value="' + name + '" autocomplete="off" class="layui-input"></div>';
            // };

            var inputContentSegment = function (thisSegmentCount, content, auto_reply_item_id, item_sort) {
                // return '<label class="layui-form-label">回复内容</label><div class="layui-input-inline" style="width: 650px;"><input type="text" id="segmentPost' + thisSegmentCount + '" name="content" placeholder="请输入回复内容" required lay-verify="required" value="' + content + '" autocomplete="off" class="layui-input"></div>';
                var html = '<label class="layui-form-label">文字</label><div class="layui-input-block"><textarea name="content" placeholder="请输入内容，不超过2000个字符" class="layui-textarea" lay-verify="content">' + content + '</textarea> </div>';
                html += '<div class="layui-form-item">' +
                    '                                    <div class="layui-inline">' +
                    '                                        <label class="layui-form-label">排序</label>' +
                    '                                        <div class="layui-input-block">' +
                    '                                            <input type="text" name="item_sort" lay-verify="title" autocomplete="off" placeholder="请输入排序数" value="' + item_sort + '" class="layui-input">' +
                    '                                        </div>' +
                    '                                    </div>' +
                    '                                </div>';
                html += '<input type="hidden" class="auto_reply_item_id" id="auto_reply_item_id' + thisSegmentCount + '" name="auto_reply_item_id" value="' + auto_reply_item_id + '">';
                return html;
            };

            var inputImageSegment = function (thisSegmentCount, content, auto_replyId, auto_reply_item_id, item_sort) {
                // return '<button type="button" class="layui-btn" id="test1">上传图片</button>';
                var html = '<div class="layui-upload"  id="image_block"><span class="layui-form-label"><button type="button" class="layui-btn  layui-btn-xs" id="test' + thisSegmentCount + '">上传图片</button></span><div class="layui-upload-list" id="image_list" style="width: 300px;">';
                if (content != '') {
                    html += '<img src="/auto_reply/getFileNameImg/' + auto_replyId + '/' + content + '" id="demo' + thisSegmentCount + '" class="layui-upload-img" style="width: 100px;">';
                } else {
                    html += '<img class="layui-upload-img" id="demo' + thisSegmentCount + '" style="width: 100px;"><p id="demoText' + thisSegmentCount + '"></p>';
                }
                html += '<div id="imageHiddenBlock' + thisSegmentCount + '" class="layui-hide"><input type="hidden" class="file_name" id="file_name' + thisSegmentCount + '" name="file_name" value="' + content + '"></div> </div> </div>';
                html += '<div class="layui-form-item">' +
                    '                                    <div class="layui-inline">' +
                    '                                        <label class="layui-form-label">排序</label>' +
                    '                                        <div class="layui-input-block">' +
                    '                                            <input type="text" name="item_sort" lay-verify="title" autocomplete="off" placeholder="请输入排序数" value="' + item_sort + '" class="layui-input">' +
                    '                                        </div>' +
                    '                                    </div>' +
                    '                                </div>';
                html += '<input type="hidden" class="auto_reply_item_id" id="auto_reply_item_id' + thisSegmentCount + '" name="auto_reply_item_id" value="' + auto_reply_item_id + '">';
                return html;
            };

            var inputAudioSegment = function (thisSegmentCount, content, auto_replyId, auto_reply_item_id, item_sort) {
                var html = '<div class="layui-upload"  id="audio_block"><span class="layui-form-label"><button type="button" class="layui-btn  layui-btn-xs" id="test' + thisSegmentCount + '">上传语音</button></span><div class="layui-upload-list" id="audio_list" style="width: 300px;">';
                html += '<p id="demoText' + thisSegmentCount + '"></p>';
                html += '<div id="audioHiddenBlock' + thisSegmentCount + '" class="layui-hide"><input type="hidden" class="file_name" id="file_name' + thisSegmentCount + '" name="file_name" value="' + content + '"></div> </div> </div>';
                html += '<div class="layui-form-item">' +
                    '                                    <div class="layui-inline">' +
                    '                                        <label class="layui-form-label">排序</label>' +
                    '                                        <div class="layui-input-block">' +
                    '                                            <input type="text" name="item_sort" lay-verify="title" autocomplete="off" placeholder="请输入排序数" value="' + item_sort + '" class="layui-input">' +
                    '                                        </div>' +
                    '                                    </div>' +
                    '                                </div>';
                html += '<input type="hidden" class="auto_reply_item_id" id="auto_reply_item_id' + thisSegmentCount + '" name="auto_reply_item_id" value="' + auto_reply_item_id + '">';
                return html;
            };

            addSegmentBtn = function (thisMessageCount, type) {
                var html = '';
                segmentCount++;
                var thisSegmentCount = segmentCount;
                html += '<div class="layui-input-inline  segment-item" style="width: 850px;" id="segment' + thisSegmentCount + '">';
                if (type == 'image') {
                    html += inputImageSegment(thisSegmentCount, '', '', 0, 0);
                } else if (type == 'audio') {
                    html += inputAudioSegment(thisSegmentCount, '', '', 0, 0);
                } else {
                    html += inputContentSegment(thisSegmentCount, '', 0, 0);
                }
                html += '</div>';
                return html;
            };

            delAutoReplyBtn = function (auto_replyId) {
                return '<button type="button" class="layui-btn layui-btn-danger layui-btn-sm" title="删除自动回复" onclick="delAutoReply(' + auto_replyId + ');"><i class="layui-icon layui-icon-close"></i></button>';
            };

            delAutoReply = function (auto_replyId) {
                layer.confirm('确认删除此自动回复？', function (index) {
                    $.ajax({
                        type: "GET",
                        url: "/auto_reply/delete/" + auto_replyId,
                        success: function (response) {
                            var dataObj = $.parseJSON(response);
                            if (dataObj.code === 0) {
                                layer.msg('删除成功', {icon: 6});
                                var targetUrl = '/auto_reply/index';
                                setTimeout(function () {
                                    location.href = targetUrl;
                                }, 1000);
                            } else {
                                layer.msg(dataObj.msg, {icon: 5});
                            }
                        },
                        error: function (request, status, error) {
                            layer.msg('哦噢，网络开小差了', {icon: 5});
                        }
                    });
                });
            };

            removeMessageBtn = function (thisMessageCount) {
                return '<button type="button" class="layui-btn layui-btn-danger layui-btn-sm" title="删除自动回复" onclick="removeMessage(' + thisMessageCount + ');"><i class="layui-icon layui-icon-close"></i></button>';
            };

            removeMessage = function (thisMessageCount) {
                layer.confirm('确认删除此自动回复？', function (index) {
                    $('#message' + thisMessageCount).remove();
                    layer.close(index);
                    // manageMessageNum('remove');
                });
            };

            addImage = function () {
                displayContent(0, '', '', 'image');
            };

            addAudio = function () {
                displayContent(0, '', '', 'audio');
            };

            addContent = function () {
                displayContent(0, '', '');
            };

            getMessages = function () {
            };
            getMessages();

            var buildMessageJson = function () {
                // var messageArray = new Array();
                var messageLines = $.find('.message-line');
                var tests = '';
                var file_names = '';
                var contents = '';
                messageLines.map(function (index, line) {
                    // var messageLineArray = new Array();
                    // var segmentArray = new Array();
                    // var segments = $(index).find('.segment-item');
                    var file_name = $(index).find('input[name="file_name"]').val();
                    var content = $(index).find('textarea[name="content"]').val();
                    var auto_reply_item_id = $(index).find('input[name="auto_reply_item_id"]').val();
                    var item_sort = $(index).find('input[name="item_sort"]').val();
                    // alert(auto_reply_item_id);
                    if (typeof (file_name) != 'undefined') {
                        tests += auto_reply_item_id + '|||' + item_sort + '|||' + file_name + '|*&';
                        // tests += '|||' +file_names;
                    }
                    if (typeof (content) != 'undefined') {
                        content = content.trim();
                        tests += auto_reply_item_id + '|||' + item_sort + '|||' + content + '|*&';
                        // tests += '|||' + contents;
                    }
                });
                return tests;
            };
        });
    </script>
</div>
</body>
</html>
